//
//  UserAccount.swift
//  WeiBoSwift
//
//  Created by Jacky Sun on 16/4/28.
//  Copyright © 2016年 syf. All rights reserved.
//

import UIKit

class UserAccount: NSObject, NSCoding {

    var access_token: String?
        /// 用户过期秒数
    var expires_in: NSNumber? {
        // expires_in 属性变化后，做些什么
        didSet {
            expires_Date = NSDate(timeIntervalSinceNow: expires_in as! Double)
        }
    }
    var uid: String?
    
    /// 过期的时间
    var expires_Date: NSDate?
   
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    /// 用户昵称
    var screen_name: String?

    
    override init() {
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }

    // 自定义构造方法
    init(dict : [String: AnyObject]) {
        
//        access_token = dict["access_token"]  as? String
//        expires_in = dict["expires_in"]  as? NSNumber
//        uid = dict["uid"]  as? String
        
        // 这样赋值后是不会调用 expires_in 的didSet 方法
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    
    override var description: String{
        // 定义属性数组
        let propertiesArr = ["access_token", "expires_in", "uid", "expires_Date", "avatar_large", "screen_name" ]
        //将属性转换成 字典
        let dict = self.dictionaryWithValuesForKeys(propertiesArr)
          return  "\(dict)"
        
    }
        
     // 归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_Date, forKey: "expires_Date")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
    }

    
    //MARK: - 解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeObjectForKey("expires_in") as? NSNumber
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_Date = aDecoder.decodeObjectForKey("expires_Date") as? NSDate
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
    }
    
    /**
     保存账户
     */
    func saveAccount() {
        
        NSKeyedArchiver.archiveRootObject(self, toFile: "account.sql".cachesPath())
    }
    
    /**
     *  取出账户信息
     */
    static var account: UserAccount?
    class func getUserAccount() ->UserAccount? {
        if account != nil {
              return account
        }
    
        account = NSKeyedUnarchiver.unarchiveObjectWithFile("account.sql".cachesPath()) as? UserAccount
        
        // 如果过期时间和现在时间,比较符合升序条件的话就是过期
        if account?.expires_Date?.compare(NSDate())  == NSComparisonResult.OrderedAscending {
            return nil
        }
        return account
    }
    
    
    /**
      判断用户是否登录
     
     - returns: true代表登录
     */
    class func isLogin() ->Bool{
         return UserAccount.getUserAccount() != nil
    }
    
    
    //MARK: -  获取用户详细资料
    func getUserDetailInfo(resulted: (newAct: UserAccount?, error: NSError?) ->()) {
        let dict = ["access_token" : access_token!, "uid" : uid!]
      
        NewWorkRequest.shareNewWorkRequest().GET("2/users/show.json", parameters: dict, success: { (_, result) in
            print(result)
            //判断字典是否有值
            if let dictt = result as? [String: AnyObject]
            {
                self.avatar_large = dictt["avatar_large"] as? String
                self.screen_name = dictt["screen_name"] as? String
                resulted(newAct: self, error: nil)
                return
            }
            resulted(newAct: nil, error: nil)
            
            }) { (_, error) in
                print(error)
                resulted(newAct: nil, error: error)
        }
    }
    
}
